package example.service.impl;

import com.alibaba.excel.EasyExcel;
import example.common.FileUtils;
import example.common.Result;
import example.common.FolderDownload;
import example.dto.*;
import example.entity.*;
import example.mapper.*;
import example.service.*;
import example.vo.SecondmentContentInfoVO;
import example.vo.SecondmentListVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class SecondmentServiceImpl implements ISecondmentService {

    @Value("${file.secondment_upload_pdf_dir}")
    private String secondmentUploadDir;

    @Value("${file.export_file_dir}")
    public String fullFilePath;

    @Resource
    private DepartmentMapper departmentMapper;

    @Resource
    private TaskListMapper taskListMapper;

    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private SecondmentContentInfoMapper secondmentContentInfoMapper;

    @Resource
    private SecondmentHeadInfoMapper secondmentHeadInfoMapper;

    @Resource
    private SecondmentMapper secondmentMapper;

    @Resource
    private SecondmentDistributeInfoMapper secondmentDistributeInfoMapper;

    @Override
    public Result addSecondment(AddSecondmentDTO addSecondmentDTO) {
        secondmentMapper.addSecondmentName(addSecondmentDTO);
        return Result.ok("新增借调事项成功！");
    }

    /**
     * 如果是一级部门 展示一级部门发布的 和二级部门请示的
     * 如果是二级部门 展示二级部门发布的 和一级部门分发的
     * 如果是三级部们 只展示分发的
     * @param
     * @return
     */
    @Override
    public Result listSecondmentByDepartmentId(GetSecListDTO getSecListDTO) {
        Long levelId = getSecListDTO.getLevelId();
        List<Secondment> sList = new ArrayList<>();
        if (levelId == 1) {
            List<Secondment> secondmentList = secondmentMapper.listSecondmentByLevel(levelId);
            // 最后只返回id和借调事项的名称的集合
            List<SecondmentListVO> secondmentListVOList = toVO(secondmentList);
            return Result.ok(secondmentListVOList);
        }
        Long departmentId = getSecListDTO.getDepartmentId();
        List<Long> secondmentIdList = secondmentDistributeInfoMapper.getSecondmentIdByDepartmentId(departmentId);
        for (Long secondmentId : secondmentIdList) {
            Secondment secondment = secondmentMapper.getById(secondmentId);
            sList.add(secondment);
        }
        if (levelId == 2) {
            List<Secondment> levelTwoSecondmentList = secondmentMapper.listById(getSecListDTO);
            Collections.reverse(levelTwoSecondmentList);
            sList.addAll(levelTwoSecondmentList);
        }
        List<SecondmentListVO> secondmentListVOList = toVO(sList);
        Collections.reverse(secondmentListVOList);
        return Result.ok(secondmentListVOList);
    }

    private List<SecondmentListVO> toVO(List<Secondment> secondmentList) {
        List<SecondmentListVO> secondmentListVOList = new ArrayList<>();
        for (Secondment secondment : secondmentList) {
            SecondmentListVO secondmentListVO = new SecondmentListVO();
            BeanUtils.copyProperties(secondment, secondmentListVO);
            secondmentListVOList.add(secondmentListVO);
        }
        return secondmentListVOList;
    }

    @Override
    public void downloadSecondmentFile(Long secondmentId, HttpServletResponse response) {
        Secondment secondment = secondmentMapper.getById(secondmentId);
        String pdfName = secondment.getPdfName();
        String pdfPath = secondment.getPdfPath();
        String[] pdfNames = pdfName.split(";"); // 分割文件名
        String[] pdfPaths = pdfPath.split(";"); // 分割文件路径
        if (pdfNames.length==1){
            FileUtils.download(pdfName, pdfPath, response);

        }else if(pdfNames.length>1){
            FileUtils.download(pdfNames, pdfPaths, response);

        }

    }

    @Override
    public ResponseEntity<byte[]> getResponseZipFile(Long secondmentId) {
        Secondment secondment = secondmentMapper.getById(secondmentId);
        String responseZipName = secondment.getResponseZipName();
        String responseZipPath = secondment.getResponseZipPath();
        try {
            return FolderDownload.downloadFolder(responseZipName, responseZipPath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public ResponseEntity<byte[]> getTempZipFile(Long secondmentId) {
        Secondment secondment = secondmentMapper.getById(secondmentId);
        String responseZipName = secondment.getResponseZipName();
        String responseZipPath = secondment.getResponseZipPath()+"\\存档材料";
        File dir = new File(responseZipPath);
        if (!dir.exists()) {
            dir.mkdirs(); // 如果文件夹不存在，则创建
        }
        try {
            return FolderDownload.downloadFolder(responseZipName, responseZipPath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Result getZipName(Long secondmentId) {
        Secondment secondment = secondmentMapper.getNameById(secondmentId);

        Date createTime = secondment.getCreateTime();
        String pattern = "yyyy年MM月dd日";

        // 创建SimpleDateFormat对象并指定日期格式
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);

        // 调用format()方法进行日期格式化
        String formattedDate = sdf.format(createTime);
        String secondmentName = secondment.getSecondmentName();
        String retName = formattedDate + " " + secondmentName;
        return Result.ok(retName);
    }

    @Override
    public Result getPdfName(Long secondmentId) {
        String pdfName = secondmentMapper.getPdfNameById(secondmentId);
        return Result.ok(pdfName);
    }

    @Override
    public Result lisSecondmentByDepartmentId(GetSecListDTO getSecListDTO) {
        Long levelId = getSecListDTO.getLevelId();
        if (levelId == 1) {
            List<Secondment> secondmentList = secondmentMapper.listSecondmentByLevel1(levelId);
            List<SecondmentListVO> secondmentListVOList = toVO(secondmentList);
            return Result.ok(secondmentListVOList);
        } else if(levelId == 2) {
            List<Secondment> secondmentList = secondmentMapper.listById(getSecListDTO);
            List<SecondmentListVO> secondmentListVOList = toVO(secondmentList);
            return Result.ok(secondmentListVOList);
        }
        return Result.ok();
    }

    @Override
    public Result uploadToLevelOne(MultipartFile file, Long secondmentId) {
        String fileName = StringUtils.cleanPath(Objects.requireNonNull(file.getOriginalFilename()));
        String responseZipPath = secondmentMapper.getResponseZipPath(secondmentId);
        String filePath = responseZipPath + "\\" + fileName;
        File newFile = new File(filePath);
        newFile.getParentFile().mkdirs();
        try {
            file.transferTo(newFile);
        } catch (IOException e) {
            return Result.fail("上传失败！");
        }
        return Result.ok("上传成功！");
    }

    @Override
    public Result updateSecondmentName(Secondment secondment) {
        secondmentMapper.updateSecondmentName(secondment);
        return Result.ok("修改成功！");
    }

    @Override
    public Result changeSecondmentState(Long secondmentId) {
        secondmentMapper.changeSecondmentState(secondmentId);
        return Result.ok("上报成功！");
    }

    @Override
    public Result searchUser(SearchSecondmentDTO searchSecondmentDTO) {
        Long levelId = searchSecondmentDTO.getLevelId();
        Long departmentId = searchSecondmentDTO.getDepartmentId();
        String name = searchSecondmentDTO.getContent();
        Set<Long> secondmentIdList = null;
        if (containsChinese(name)) {
            if (levelId == 1) {
                secondmentIdList = secondmentContentInfoMapper.searchSecondmentIdByName1(searchSecondmentDTO);
            }else if (levelId == 2){
                String departmentName = departmentMapper.getDepartmentNameById(departmentId);
                secondmentIdList = secondmentMapper.getSecondmentIdByDepartmentName(departmentName);
                secondmentIdList.addAll(secondmentContentInfoMapper.searchSecondmentIdByName(searchSecondmentDTO));
            }
            else {
                secondmentIdList = secondmentContentInfoMapper.searchSecondmentIdByName(searchSecondmentDTO);
            }
        } else {
            if ( levelId == 1) {
                secondmentIdList = secondmentContentInfoMapper.searchSecondmentIdByNumber1(searchSecondmentDTO);
            }else if (levelId == 2){
                String departmentName = departmentMapper.getDepartmentNameById(departmentId);
                secondmentIdList = secondmentMapper.getSecondmentIdByDepartmentName(departmentName);
                secondmentIdList.addAll(secondmentContentInfoMapper.searchSecondmentIdByNumber(searchSecondmentDTO));
            }
            else {
                secondmentIdList = secondmentContentInfoMapper.searchSecondmentIdByNumber(searchSecondmentDTO);
            }
        }
        List<Secondment> secondmentList = new ArrayList<>();
        for (Long secondmentId : secondmentIdList) {
            Secondment secondment = secondmentMapper.getById(secondmentId);
            secondmentList.add(secondment);
        }
        List<SecondmentListVO> secondmentListVOList = toVO(secondmentList);
        Collections.reverse(secondmentListVOList);
        return Result.ok(secondmentListVOList);
    }
    @Override
    public Result changeConfirmState(SecondmentConfirmDTO secondmentConfirmDTO){
        List<SecondmentContentInfoVO> secondmentContentInfoVOList = new ArrayList<SecondmentContentInfoVO>();
        //这里获取的应该只有已同意的人员
        secondmentContentInfoVOList = secondmentContentInfoMapper.getSecondmentContentBySecondmentIdAndNameAndState(secondmentConfirmDTO);
        if (secondmentConfirmDTO.getConfirm().equals("审核通过")){
            // 审核通过，将该部门该事件的人的状态改为已借调，存入历史借调
            try {
                for (SecondmentContentInfoVO secondmentContentInfoVO : secondmentContentInfoVOList) {
                    //首先把confirm状态改为1
                    secondmentContentInfoMapper.changeConfirm(secondmentContentInfoVO.getId());
                    //存入task表
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

                    String currentDateStr = sdf.format(new Date());
                    Date currentDate = sdf.parse(currentDateStr);
                    String lastTime = secondmentContentInfoVO.getSecondmentLastTime();
                    Date endDate = sdf.parse(toEndTime(currentDateStr, lastTime));
                    Secondment sec = secondmentMapper.getById(secondmentContentInfoVO.getSecondmentId());

                    TaskList taskList = new TaskList();
                    taskList.setSecondmentId(secondmentContentInfoVO.getSecondmentId());
                    taskList.setDepartmentName(secondmentContentInfoVO.getDepartmentName());
                    taskList.setSecondmentCreateDepartmentName(sec.getDepartmentName());
                    taskList.setTaskName(sec.getSecondmentName());

                    taskList.setName(secondmentContentInfoVO.getUserName());
                    taskList.setUserId(secondmentContentInfoVO.getUserId());
                    taskList.setSecondmentDate(currentDate);
                    taskList.setSecondmentLastTime(lastTime);
                    taskList.setEndTime(endDate);
                    taskList.setSecondmentState("待下发命令");

                    taskListMapper.insertTaskList(taskList);
                    //user表也改为已借调
                    UserInfo userInfo = new UserInfo();
                    userInfo.setState("已借调");
                    userInfo.setUserId(secondmentContentInfoVO.getUserId());
                    userInfoMapper.saveInfo(userInfo);
                }
                SecondmentDistributeInfo secondmentDistributeInfo = new SecondmentDistributeInfo();
                secondmentDistributeInfo.setDepartmentId(secondmentConfirmDTO.getDepartmentId());
                secondmentDistributeInfo.setSecondmentId(secondmentConfirmDTO.getSecondmentId());
                secondmentDistributeInfo.setConfirm(secondmentConfirmDTO.getConfirm());
                secondmentDistributeInfoMapper.changeConfirmState(secondmentDistributeInfo);

            } catch (Exception e) {
                e.printStackTrace();
                return Result.fail("审核失败！");
            }
            return Result.ok("审核成功！");
        }
        if (secondmentConfirmDTO.getConfirm().equals("驳回")){
            SecondmentDistributeInfo secondmentDistributeInfo = new SecondmentDistributeInfo();
            secondmentDistributeInfo.setDepartmentId(secondmentConfirmDTO.getDepartmentId());
            secondmentDistributeInfo.setSecondmentId(secondmentConfirmDTO.getSecondmentId());
            secondmentDistributeInfo.setConfirm("未处理");
            secondmentDistributeInfoMapper.changeConfirmState(secondmentDistributeInfo);
            secondmentDistributeInfo.setResponseState("未上报");
            secondmentDistributeInfoMapper.changeResState(secondmentDistributeInfo);
            for (SecondmentContentInfoVO secondmentContentInfoVO : secondmentContentInfoVOList) {
                //把每个人的确认状态改为0、
                secondmentContentInfoMapper.setConfirm(secondmentContentInfoVO.getId());
                //用户表取消借调状态
                UserInfo userInfo = new UserInfo();
                userInfo.setName(secondmentContentInfoVO.getUserName());
                userInfo.setUserId(secondmentContentInfoVO.getUserId());
                userInfoMapper.cancelSecondment(userInfo);
                //删除该借调任务
                TaskList taskList = new TaskList();
                taskList.setName(secondmentContentInfoVO.getUserName());
                taskList.setSecondmentId(secondmentContentInfoVO.getSecondmentId());
                taskListMapper.cancelSecondment(taskList);
            }
        }
        return Result.ok("驳回成功！");
    }

    /** 这个功能没用 */
    @Override
    public Result confirmSecondment(Long id) {
        SecondmentContentInfo secondmentContentInfo = secondmentContentInfoMapper.getUserInfoById(id);
        UserInfo userInfo = new UserInfo();
        userInfo.setName(secondmentContentInfo.getUserName());
        userInfo.setUserId(secondmentContentInfo.getUserId());
        userInfo.setState("已借调");
        userInfoMapper.saveInfo(userInfo);
        secondmentContentInfoMapper.changeConfirm(id);
        return Result.ok("成功！");
    }
     //判断是否借调成功
    @Override
    public Result getC(SecondmentContentInfo secondmentContentInfo) {
        String departmentName = secondmentContentInfo.getDepartmentName();
        Long secondmentId = secondmentContentInfo.getSecondmentId();
        Secondment departmentCreatSecondment = secondmentMapper.getById(secondmentId);
        List<Boolean> confirm;
        if (departmentCreatSecondment.getDepartmentName().equals(departmentName)){
          confirm = secondmentContentInfoMapper.getCById(secondmentContentInfo);
        }else{
          confirm = secondmentContentInfoMapper.getC(secondmentContentInfo);
        }

        for (Boolean b : confirm) {
            if (b) return Result.ok(1);
        }
        return Result.ok(2);
    }

    @Override
    public void downloadConfirm(Long secondmentId, HttpServletResponse response) {
        Secondment secondment = secondmentMapper.getById(secondmentId);
        String confirmName = secondment.getConfirmName();
        String confirmPath = secondment.getConfirmPath();
        if (confirmName != null && confirmPath != null) {
            FileUtils.download(confirmName, confirmPath, response);
        }
    }

    @Override
    public Result getConfirmName(Long secondmentId) {
        String confirmName = secondmentMapper.getConfirmName(secondmentId);
        return Result.ok(confirmName);
    }

    public Result onedepartConfirmSecondment(MultipartFile file, Long secondmentId,Long departmentId){
        if (null == file) {
            return Result.fail("请上传文件！");
        }
        try {
            String fileName = StringUtils.cleanPath(file.getOriginalFilename());
            String filePath = secondmentUploadDir + "\\" + fileName;
            File newFile = new File(filePath);
            newFile.getParentFile().mkdirs();
            file.transferTo(newFile);

           SecondmentDistributeInfo secondmentDistributeInfo = new SecondmentDistributeInfo();
            secondmentDistributeInfo.setSecondmentId(secondmentId);
            secondmentDistributeInfo.setDepartmentId(departmentId);
            secondmentDistributeInfo.setConfirmName(fileName);
            secondmentDistributeInfo.setConfirmPath(filePath);
            secondmentDistributeInfoMapper.saveOneDepartmentConfirm(secondmentDistributeInfo);
            //将军官借调状态由待下发命令改为借调成功
            TaskList taskList = new TaskList();
            taskList.setSecondmentId(secondmentId);
            taskList.setSecondmentState("借调成功");
            taskList.setDepartmentName(departmentMapper.getDepartmentNameById(departmentId));
            taskListMapper.updateSencondmentStateBySecondmentIdAndDepartmentId(taskList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("文件上传失败！");
        }
        return Result.ok("文件上传成功！");
    }

    @Override
    public  Result alldepartConfirmSecondment(MultipartFile file, Long secondmentId){
        if (null == file) {
            return Result.fail("请上传文件！");
        }
        try {
            String fileName = StringUtils.cleanPath(file.getOriginalFilename());
            String filePath = secondmentUploadDir + "\\" + fileName;
            File newFile = new File(filePath);
            newFile.getParentFile().mkdirs();
            file.transferTo(newFile);

            Secondment secondment = new Secondment();
            secondment.setId(secondmentId);
            secondment.setConfirmName(fileName);
            secondment.setConfirmPath(filePath);
            secondmentMapper.saveConfirmPdfInfoById(secondment);

            //将该借调事件的状态改为借调成功
            TaskList taskList = new TaskList();
            taskList.setSecondmentState("借调成功");
            taskList.setSecondmentId(secondmentId);
            taskListMapper.updateSencondmentStateBySecondmentId(taskList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("文件上传失败！");
        }
        return Result.ok("文件上传成功！");
    }

    @Override
    public Result singleConfirmSecondment(MultipartFile file, Long secondmentId, Long id) {
        // 一种情况是state是null（没被借调） 另一种情况是 时间已经过期了

        if (null == file) {
            return Result.fail("请上传文件！");
        }
        try {
            SecondmentContentInfo secondmentContentInfo = secondmentContentInfoMapper.getUserInfoById(id);

            TaskList ta = new TaskList();
            ta.setUserId(secondmentContentInfo.getUserId());
            String tTime = taskListMapper.getEndTime(ta);
            if (null != tTime) {
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
                LocalDateTime d1 = LocalDate.parse(tTime, formatter).atStartOfDay();
                LocalDateTime currentDateTime = LocalDateTime.now();
                LocalDateTime d2 = currentDateTime.truncatedTo(java.time.temporal.ChronoUnit.DAYS);

                if (d2.isBefore(d1)) {
                    return Result.fail("已被借调！");
                }
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            String currentDateStr = sdf.format(new Date());
            Date currentDate = sdf.parse(currentDateStr);
            String lastTime = secondmentContentInfo.getSecondmentLastTime();
            Date date = sdf.parse(toEndTime(currentDateStr, lastTime));
            Secondment sec = secondmentMapper.getById(secondmentId);

            TaskList taskList = new TaskList();
            taskList.setSecondmentId(secondmentId);
            taskList.setDepartmentName(sec.getDepartmentName());
            taskList.setTaskName(sec.getSecondmentName());

            taskList.setName(secondmentContentInfo.getUserName());
            taskList.setUserId(secondmentContentInfo.getUserId());
            taskList.setSecondmentDate(currentDate);
            taskList.setSecondmentLastTime(lastTime);
            taskList.setEndTime(date);

            taskListMapper.saveTask(taskList);
            UserInfo userInfo = new UserInfo();
            userInfo.setState("已借调");
            userInfo.setUserId(secondmentContentInfo.getUserId());
            userInfoMapper.saveInfo(userInfo);
            secondmentContentInfoMapper.changeConfirm(id);

            String fileName = StringUtils.cleanPath(file.getOriginalFilename());
            String filePath = secondmentUploadDir + "\\" + fileName;
            File newFile = new File(filePath);
            newFile.getParentFile().mkdirs();
            file.transferTo(newFile);

            Secondment secondment = new Secondment();
            secondment.setId(secondmentId);
            secondment.setConfirmName(fileName);
            secondment.setConfirmPath(filePath);
            secondmentMapper.saveConfirmPdfInfoById(secondment);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("文件上传失败！");
        }
        return Result.ok("文件上传成功！");
    }

    @Override
    @Transactional
    public void export(ExportExcelDTO exportExcelDTO, HttpServletResponse response) {

        // 先写第一部门的 不同意的也全部导出
        Long secondmentId = exportExcelDTO.getSecondmentId();
        Long levelId = exportExcelDTO.getLevelId();
        List<SecondmentContentInfo> secondmentContentInfoList;
        if (levelId == 1L||levelId == 2L) {
            //根据借调ID获取借调详情
            secondmentContentInfoList = secondmentContentInfoMapper.getAllExportExcelInfo(exportExcelDTO);
        } else {
            //根据借调ID和所属部门获取借调详情
            secondmentContentInfoList = secondmentContentInfoMapper.getExportExcelInfo(exportExcelDTO);
        }
        List<ExportExcel> exportExcelList = new ArrayList<>();
        int idx = 1; // 序号
        //根据借调详情设置excel数据
        for (SecondmentContentInfo secondmentContentInfo : secondmentContentInfoList) {
            ExportExcel exportExcel = new ExportExcel();
            // 身份证
            exportExcel.setIdentity(secondmentContentInfo.getUserId());
            // 姓名
            exportExcel.setName(secondmentContentInfo.getUserName());

            /** 上传excel的时候需要保存 */
            //需修改判断是否用户表中有该用户的信息
            UserInfo user = userInfoMapper.getByUserId(secondmentContentInfo.getUserId());
            // 岗位职务
            exportExcel.setJob(user.getJob());
            // 军衔
            exportExcel.setPartyLevel(user.getPartyLevel());
            // 职务层级
            exportExcel.setJobLevel(user.getJobLevel());
            //计算该军衔和职务层级被借调次数
            Integer pTime = userInfoMapper.getPartyTime(user)==null? 0:userInfoMapper.getPartyTime(user);
            Integer jTime = userInfoMapper.getJobTime(user)==null? 0:userInfoMapper.getJobTime(user);
            // 本衔级/职级被借调次数
            String times = "" + pTime + "/" + jTime;
            exportExcel.setTimes(times);

            TaskList task = new TaskList();
            task.setUserId(user.getUserId());
            task.setSecondmentId(secondmentId);
            //查询该用户在其他借调事件中是否被借调
            TaskList taskList = taskListMapper.getPastTask(task);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            if (null != taskList) {
                // 借调单位(已参加)
                exportExcel.setPastDepartment(taskList.getSecondmentCreateDepartmentName());
                if (departmentMapper.getLevelIdByName(taskList.getSecondmentCreateDepartmentName())==1){
                    exportExcel.setPastType("军委机关");
                }else{
                    exportExcel.setPastType("军航机关");
                }
                // 机关类型(已参加)
//                exportExcel.setPastType(taskList.getDepartmentType());
                // 任务名称(已参加)
                exportExcel.setPastSecondmentName(taskList.getTaskName());
                // 借调起时(已参加)

                String formattedBeginTime = sdf.format(taskList.getSecondmentDate());
                exportExcel.setPastBeginTime(formattedBeginTime);
                // 借调止时(已参加)
                exportExcel.setPastEndTime(sdf.format(taskList.getEndTime()));
            }else{
                exportExcel.setPastDepartment("*");
                exportExcel.setPastType("*");
                exportExcel.setPastType("*");
                exportExcel.setPastSecondmentName("*");
                exportExcel.setPastBeginTime("*");
                exportExcel.setPastEndTime("*");
            }

             //获取部门人数
            Integer employeeNumber = departmentMapper.getEmployeeNumber(user.getDepartmentName());
            //查找该部门已借调的人数
            Integer secondmentNumber = userInfoMapper.getSecondmentEd(user.getDepartmentName());
            Integer maxSecondmentNumber = (int)(1.0 * employeeNumber * 0.02);
            double percentage = ((double) secondmentNumber / employeeNumber) * 100;
            String formattedPercentage = String.format("%.1f", percentage); // 保留一位小数
            int res = maxSecondmentNumber - secondmentNumber;
            String str = "还可以借调" + res + "人";
            String percent = user.getDepartmentName()+"军官编制" + employeeNumber + "人，可借调" + maxSecondmentNumber +"人，已借调"+ secondmentNumber+"人，借调后比例为"+formattedPercentage+"%";
            // 借调比例情况
            exportExcel.setPercent(percent);
            //现在要参加的当前借调事件
            TaskList nowTask = taskListMapper.getNowTask(task);
            if (null != nowTask) {
                // 借调单位(拟参加)
                exportExcel.setDepartment(nowTask.getSecondmentCreateDepartmentName());
                if (departmentMapper.getLevelIdByName(nowTask.getSecondmentCreateDepartmentName())==1){
                    exportExcel.setType("军委机关");
                }else{
                    exportExcel.setType("军航机关");
                }
                // 机关类型(拟参加)
//                exportExcel.setType(nowTask.getDepartmentType());
                // 任务名称(拟参加)
                exportExcel.setSecondmentName(nowTask.getTaskName());
                // 借调起时(拟参加)
                exportExcel.setBeginTime(sdf.format(nowTask.getSecondmentDate()));
                // 借调止时(拟参加)
                exportExcel.setEndTime(sdf.format(nowTask.getEndTime()));
                // 借调时间(拟参加)
                exportExcel.setLastTime(nowTask.getSecondmentLastTime());
            }else{
                SecondmentContentInfo prepareTask = secondmentContentInfoMapper.getNowTask(task);
                if (null != prepareTask) {
                    // 借调单位(拟参加)
                    Secondment secondment = secondmentMapper.getById(prepareTask.getSecondmentId());
                    exportExcel.setDepartment(secondment.getDepartmentName());
                    if (departmentMapper.getLevelIdByName(secondment.getDepartmentName())==1){
                        exportExcel.setType("军委机关");
                    }else{
                        exportExcel.setType("军航机关");
                    }
                    // 机关类型(拟参加)
//                exportExcel.setType(nowTask.getDepartmentType());
                    // 任务名称(拟参加)
                    exportExcel.setSecondmentName(secondment.getSecondmentName());
                    // 借调起时(拟参加)
                    exportExcel.setBeginTime(prepareTask.getSecondmentDate());
                    // 借调止时(拟参加)
                    exportExcel.setEndTime("*");
                    // 借调时间(拟参加)
                    exportExcel.setLastTime(prepareTask.getSecondmentLastTime());
                }else{
                    exportExcel.setDepartment("*");
                    exportExcel.setSecondmentName("*");
                    exportExcel.setType("*");
                    // 借调起时(拟参加)
                    exportExcel.setBeginTime("*");
                    // 借调止时(拟参加)
                    exportExcel.setEndTime("*");
                    // 借调时间(拟参加)
                    exportExcel.setLastTime("*");
                }

            }
            String state = secondmentContentInfo.getState();
            if (state.equals("同意")) {
                exportExcel.setCondition("符合");
            } else {
                exportExcel.setCondition("不符合");
            }
            // 是否符合条件

            // 借调意见
            exportExcel.setOpinion(state);
            // 备注
            exportExcel.setTips(secondmentContentInfo.getTips()==null?"*":secondmentContentInfo.getTips());
            exportExcelList.add(exportExcel);
            exportExcel.setId(idx++);
        }
        //获取数据
        try{
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode("学生表.xls","utf-8"));

            //获取模板路径
            Map<String, Object> map = new HashMap<>();
            map.put("num", idx-1);
            //输出excel
            EasyExcel
                    .write(response.getOutputStream())
                    .autoCloseStream(true)
                    .withTemplate(fullFilePath)
                    .build()
                    .fill(exportExcelList, EasyExcel.writerSheet(0).build())
                    .fill(map, EasyExcel.writerSheet(0).build())
                    .finish();
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new RuntimeException(e);
        }
    }

    private String toEndTime(String currentDate, String lastTime) {
        int m = 0;
        for (int i = 0; i < lastTime.length(); i++) {
            char ch = lastTime.charAt(i);
            if (ch >= '0' && ch <= '9') {
                m = m * 10 + (ch - '0');
            }
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        LocalDate date = LocalDate.parse(currentDate, formatter);
        LocalDate date1 = date.plusMonths(m);
        return date1.format(formatter);
    }

    public static boolean containsChinese(String str) {
        String regex = "[\u4e00-\u9fa5]";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        return matcher.find();
    }

    @Override
    @Transactional
    public Result deleteSecondment(Long secondmentId) {

        // 首先删除secondment表 把里面的整文件夹 和 pdf删除就好
        try {
            Secondment secondment = secondmentMapper.getById(secondmentId);
            String pdfPath = secondment.getPdfPath();
            String confirmPath = secondment.getConfirmPath();
            String responseZipPath = secondment.getResponseZipPath();
            secondmentMapper.deleteBySecondmentId(secondmentId);
            if (pdfPath != null) FileUtils.deleteFileOrDirectory(new File(pdfPath));
            if (confirmPath != null) FileUtils.deleteFileOrDirectory(new File(confirmPath));
            if (responseZipPath != null) FileUtils.deleteFileOrDirectory(new File(responseZipPath));
            secondmentContentInfoMapper.deleteBySecondmentId(secondmentId);
            secondmentHeadInfoMapper.deleteBySecondmentId(secondmentId);
            secondmentDistributeInfoMapper.deleteBySecondmentId(secondmentId);
            return Result.ok("删除成功！");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.fail("删除失败！");
        }
    }
}
